import axios from 'axios'
import QS from 'qs';

axios.defaults.baseURL = '/api'
axios.interceptors.request.use(
    config => {
        // 每次发送请求之前判断vuex中是否存在token        
        // 如果存在，则统一在http请求的header都加上token，这样后台根据token判断你的登录情况
        // 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断 
        const token = window.localStorage.getItem('token') || '';
        config.headers = {
            'Content-Type': 'application/json',
            'Authorization': token
        }
        return config;
    },
    error => {
        return Promise.error(error);
    })

axios.interceptors.response.use(
    response => {
        // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
);
export function get(url, params) {
    console.log(params);
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: { params }
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            console.log(err);
            reject(err.data)
        })
    });
}

export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}
export function $delete(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete().then().catch()
    })
}
export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios.put().then().catch()
    })
}